using System.Collections.Generic;
using Cysharp.Threading.Tasks;
using Framework.Interface;
using Framework.StateMechine;
using Shared.UI;
using UnityEngine;

namespace Game.Hotfix
{
    public class Hotfix : IApp
    {
        public HotfixServerDto hotfixServerDto;
        public int engineVersion;
        public int hotfixVersion;
        
        public Dictionary<string, ChecksumData> localChecksum;      // 本地的 checksum
        public Dictionary<string, ChecksumData> remoteChecksum;     // 请求得到的 服务器的checksum
        
        public float downloadSize;                                  // 下载资源的大小
        public List<ChecksumData> downLoadList;                     // 需要下载的列表
        public byte[] remoteChecksumData;                           // 远程checksum数据

        public bool hotfixEnd;                                      // 结束
        
        private StateMachine stateMechine;
        
        public Hotfix()
        {
            Reset();
        }

        ~Hotfix()
        {
            RecordLoaded();
            Reset();
            Debug.Log("hotfix destroy.");
        }

        public async UniTask Start()
        {
            hotfixEnd = false;

            stateMechine = new StateMachine(this);
            await stateMechine.Add(HotfixState.Prepare, new HotfixPrepare());
            await stateMechine.Add(HotfixState.Reinstall, new HotfixReinstall());
            await stateMechine.Add(HotfixState.VerifyVersion, new HotfixVerifyVersion());
            await stateMechine.Add(HotfixState.LoadChecksum, new HotfixLoadChecksum());
            await stateMechine.Add(HotfixState.VerifyChecksum, new HotfixVerifyChecksum());
            await stateMechine.Add(HotfixState.DownloadRemote2Local, new HotfixDownloadRemote2Local());
            await stateMechine.Add(HotfixState.Result, new HotfixResult());
            await stateMechine.Add(HotfixState.End, new HotfixEnd());
            await stateMechine.Run(HotfixState.Prepare);

            await UniTask.WaitUntil(Update);
        }

        private bool Update()
        {
            if (stateMechine != null)
                stateMechine.Update();

            return hotfixEnd;
        }

        private void RecordLoaded()
        {
            
        }

        private void Reset()
        {
            hotfixServerDto = null;
            engineVersion = 0;
            hotfixVersion = 0;
            localChecksum = new Dictionary<string, ChecksumData>();
            remoteChecksum = new Dictionary<string, ChecksumData>();
            downloadSize = 0;
            downLoadList = new List<ChecksumData>();
        }
    }
}